package com.arvato.wxwork.controller.front.member;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.arvato.common.config_bean.ZSTBrandNumberConfig;
import com.arvato.minipro.bean.bean_dto.common.Result;
import com.arvato.wxwork.bean.bean_do.member.WxworkExternalInfoDo;
import com.arvato.wxwork.bean.bean_dto.MemberShowInfoDto;
import com.arvato.wxwork.bean.bean_vo.member.WxworkExternalInfoVo;
import com.arvato.wxwork.service.member.WxworkExternalService;
import com.arvato.wxwork.service.member.WxworkMemberInfoService;
import com.arvato.wxwork.service.other.WxworkProvinceCityService;


/**
 * 资生堂企业微信会员接口(获取会员的详情，订单信息，积分历史等等)
 * @author ZHAN655
 */
@RestController
@RequestMapping("/wxwork/member")
public class WxworkMemberController{
	
	private Logger logger = LoggerFactory.getLogger(WxworkMemberController.class);
	@Autowired
	private WxworkMemberInfoService wxworkMemberInfoService;

	@Autowired
	private WxworkExternalService wxworkExternalService;
	
	@Autowired
	private WxworkProvinceCityService wxworkProvinceCityService;
	
	/**
	 * 查询一个外部联系人是不是品牌的会员
	 * 如果是会员返回会员号，
	 * 否则返回不是会员
	 * @param req
	 * @param externalId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value="/baseinfo")
	public Result baseInfo(HttpServletRequest req, String externalId) {
		logger.info("");
		// 首先根据externalId查出该外部联系人在本系统的unionid 还有brand
		WxworkExternalInfoVo externalVo = wxworkExternalService.getExternalById(externalId);
		String memberId = externalVo.getMemberId();
		if(memberId != null && !memberId.equals("")) {
			return  Result.success(memberId);
		}
		Map<String, Object> resultMap = wxworkMemberInfoService.getMemberBaseInfo(externalVo.getUnionid(), externalVo.getBrand());
		// 当查询返回码不是S01的时候，查询会员信息失败
		if(!"S01".equals(resultMap.get("StatusCode") + "")) {
			return Result.fail("获取用户会员信息失败或者该会员不存在", resultMap);
		}
		Map<String, Object> resultDataMap = (Map<String, Object>)resultMap.get("Data");
		List<Map<String,Object>> resultDataList = (List<Map<String,Object>>)resultDataMap.get("item");
		if(resultDataList != null && resultDataList.size() > 0) {
			System.out.println("用户的会员ID查询成功：" + resultDataList.get(0).get("memberId"));
			memberId = resultDataList.get(0).get("memberId") + "";
			// 查询成功之后 将此次请求的会员ID存起来 防止下次再请求
			WxworkExternalInfoDo externalDo = new WxworkExternalInfoDo();
			externalDo.setExternalId(externalId);
			externalDo.setMemberId(memberId);
			try {
				wxworkExternalService.update(externalDo);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return Result.success(resultDataList.get(0));
		}
		return Result.fail("获取用户会员信息失败或者该会员不存在", resultMap);
	}
	
	/**
	 * 获取会员信息
	 * @param orderId
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping("/info")
    public Result getRemoteMemberInfo(String externalId) throws IllegalAccessException, InvocationTargetException{
		WxworkExternalInfoVo externalVo = wxworkExternalService.getExternalById(externalId);
		String brand = externalVo.getBrand();
		MemberShowInfoDto memberInfoDto = new MemberShowInfoDto();
		BeanUtils.copyProperties(memberInfoDto, externalVo);
		// 如果是会员那么就查询该会员的积分，会员等级等信息
		String memberId = externalVo.getMemberId();
		if(memberId != null && !memberId.equals("")) {
			// 获取会员当前积分
			Map<String, Object> pointMap = wxworkMemberInfoService.getMemberPoint(memberId, brand);
			Map<String, Object> pointDataMap = (Map<String, Object>)pointMap.get("Result");
			Map<String, Object> currentPointInfoMap = (Map<String, Object>)pointDataMap.get("CurrentPointInfo");
			if(currentPointInfoMap != null) {
				String point = currentPointInfoMap.get("Point") + "";
				memberInfoDto.setPoint(point);
			}
			Map<String, Object> resultMap = wxworkMemberInfoService.getMemberInfo(memberId, brand);
			Map<String, Object> dataMap = (Map<String, Object>)resultMap.get("Result");
			Map<String, Object> memberInfo = (Map<String, Object>)dataMap.get("MemberInfo");
			if(memberInfo != null) {
				String birthDay = memberInfo.get("Birthday") + "";
				Calendar now = Calendar.getInstance();  
				int year = now.get(Calendar.YEAR);
				String provinceCode = memberInfo.get("Province") + "";
				String cityCode = memberInfo.get("City") + "";
				String provinceName = wxworkProvinceCityService.getProvinceName(provinceCode);
				String cityName = wxworkProvinceCityService.getCityName(provinceCode, cityCode);
				memberInfoDto.setMemberType(ZSTBrandNumberConfig.BRAND_MEMBER_MAP.get(brand + "_" + memberInfo.get("MemberType"))); 
				memberInfoDto.setBirthDay(birthDay);
				memberInfoDto.setAge(year - Integer.valueOf(birthDay.substring(0,4)));
				memberInfoDto.setRegisteType(memberInfo.get("RegisteType") + "");
				memberInfoDto.setProvinceName(provinceName);
				memberInfoDto.setCityName(cityName);
				memberInfoDto.setAddress(memberInfo.get("Address") + "");
				memberInfoDto.setMobile(memberInfo.get("Mobile") + "");
			}
		}
		return Result.success(memberInfoDto);
    }
	
	/**
	 * 获取用户的订单列表
	 * @param memberId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping("/order/list")
    public Result getRemoteCustomerOrders(String memberId){
		Map<String, Object> resultMap = wxworkMemberInfoService.getMemberOrderIist(memberId);
		if(!"S01".equals(resultMap.get("StatusCode") + "")) {
			return Result.fail("获取订单列表失败", resultMap);
		}
		try {
			Map<String, Object> map = (Map<String, Object>)resultMap.get("Data");
			ArrayList<Map<String, Object>> orderList = (ArrayList<Map<String, Object>>)map.get("item");
			for(Map<String, Object> orderItem : orderList) {
				String orderDate = orderItem.get("orderdate") + "";
				if(orderDate != null && !orderDate.equals("null")) {
					orderItem.put("orderdate", orderDate.substring(0,10));
				}
				Map<String, Object> orderDetail = wxworkMemberInfoService.getMemberOrderDetail(orderItem.get("orderid") + "");
				if("S01".equals(resultMap.get("StatusCode") + "")) {
					Map<String, Object> orderDetailMap = (Map<String, Object>)orderDetail.get("Data");
					ArrayList<Map<String, String>> commodityList = (ArrayList<Map<String, String>>)orderDetailMap.get("item");
					orderItem.put("commodityList", commodityList);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("调用CRM订单接口，数据解析出错。");
			return Result.success(resultMap.get("Data"));
		}
		// 遍历List 查询订单明细
		return Result.success(resultMap.get("Data"));
	}
	
	/**
	 * 获取订单详情
	 * @param orderId
	 * @return
	 */
	@ResponseBody
    @RequestMapping("/order/detail")
    public Result getRemoteOrderDetails(String orderId){
    	Map<String, Object> resultMap = wxworkMemberInfoService.getMemberOrderDetail(orderId);
		if(!"S01".equals(resultMap.get("StatusCode") + "")) {
			return Result.fail("获取订单详情失败", resultMap);
		}
		return Result.success(resultMap.get("Data"));
    }
	
	/**
     * 获取用户当前积分
     * @param memberId 会员编号(调用外部接口可获得)
     * @param brand 品牌
     * @return
     */
	@ResponseBody
    @RequestMapping("/point")
    public Result getPoint(String memberId, String brand){
		Map<String, Object> pointMap = wxworkMemberInfoService.getMemberPoint(memberId, brand);
		if(pointMap != null) {
			return Result.success(pointMap);
		}
		return Result.fail("获取积分失败");
    }
	
    /**
     * 获取用户积分历史
     * @param memberId 会员编号(调用外部接口可获得)
     * @return
     */
	@ResponseBody
    @RequestMapping("/point/history")
    public Result getPointHistory(String memberId){
    	Map<String, Object> resultMap = wxworkMemberInfoService.getMemberPointHistory(memberId);
    	if(!"S01".equals(resultMap.get("StatusCode") + "")) {
			return Result.fail("获取积分历史失败", resultMap);
		}
		return Result.success(resultMap.get("Data"));
    }
	
    /**
     * 获取用户礼品领用历史
     * @param memberId
     * @return
     */
	@ResponseBody
    @RequestMapping("/gifts")
    public Result getGifts(String memberId){
    	Map<String, Object> resultMap = wxworkMemberInfoService.getMemberGifts(memberId);
    	if(!"S01".equals(resultMap.get("StatusCode") + "")) {
			return Result.fail("获取用户礼品领用历史失败", resultMap);
		}
		return Result.success(resultMap.get("Data"));
    }
	
	 /**
     * 获取用户礼品领用历史
     * @param memberId
     * @return
     */
	@ResponseBody
    @RequestMapping("/habits")
    public Result getHabits(String memberId){
    	Map<String, Object> resultMap = wxworkMemberInfoService.getMemberHabits(memberId);
    	if(!"S01".equals(resultMap.get("StatusCode") + "")) {
			return Result.fail("获取用户偏好失败", resultMap);
		}
		return Result.success(resultMap.get("Data"));
    }
}
